package com.itheima.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Result;
import com.itheima.service.PermissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/permission")
public class PermissionController {
    @Autowired
    private PermissionService permissionService;

    @PostMapping("/add")
    public Result add(@RequestBody Permission permission) {
        permissionService.save(permission);
        return Result.success("成功");
    }

    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Long id) {
        permissionService.removeById(id);
        return Result.success("成功");
    }

    @PutMapping("/put/{id}")
    public Result update(@PathVariable Long id, @RequestBody Permission permission) {
        // 校验 ID 是否匹配
        if (id == null) {
            return Result.error("请求的ID与数据中ID不一致");
        }

        // 更新操作
        boolean isUpdated = permissionService.updateById(permission);

        if (isUpdated) {
            return Result.success("成功");
        } else {
            return Result.error("更新失败");
        }
    }

    // 获取权限信息
    @GetMapping("/detail/{id}")
    public Result getPermissionById(@PathVariable Long id) {
        // 根据 ID 查询权限信息
        Permission permission = permissionService.getById(id);

        // 如果没有找到对应的权限信息，返回错误信息
        if (permission == null) {
            return Result.error("未找到该权限信息");
        }

        // 返回成功的响应，包含权限信息
        return Result.success(permission);
    }

    @GetMapping("/list")
    public Result<Page> page(Integer page, Integer pagesize,Integer enVisible) {
        Page page1 = new Page(page, pagesize);
        return permissionService.selectPage(page1,enVisible);
    }

}
